package com.example.demo.base.filter;

import com.example.demo.base.bean.BaseResp;
import com.example.demo.base.exceptions.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * Created by yingzhi zhu on 2017/9/17.
 *
 * @author yingzhi zhu
 * 对返回的异常进行统一处理
 */
@RestControllerAdvice
public class ExceptionAdvice {

    Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    /**
     * 自定义BaseException 进行处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BaseException.class)
    public BaseResp baseExceptionHandler(BaseException e) {
        logger.error("Customer Exception --------------------CODE:{} MESSAGE:{} ",
                e.getCode(), e.getMessage());
        BaseResp baseResp = new BaseResp();
        baseResp.setCode(e.getCode());
        baseResp.setStatus(e.getStatus());
        baseResp.setMessage(e.getMessage());
        return baseResp;
    }

    /**
     * 除了BaseException 所有异常的处理
     */
    @ExceptionHandler(Exception.class)
    public BaseResp otherExceptionHandler(Exception e) {
        e.printStackTrace();
        BaseResp baseResp = new BaseResp();
        baseResp.setCode(0);
        baseResp.setStatus(500);
        baseResp.setMessage(e.getMessage());
        return baseResp;
    }

//    /**
//     * 除了BaseException 所有异常的处理
//     */
//    @ExceptionHandler(DataIntegrityViolationException.class)
//    public BaseResp otherExceptionHandler(DataIntegrityViolationException e){
//        e.printStackTrace();
//        BaseResp baseResp = new BaseResp();
//        baseResp.setMeta(Meta.IsRegisterError);
//        return baseResp;
//    }

}
